package com.ruanjian.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.ruanjian.reggie.common.R;
import com.ruanjian.reggie.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

/*
* 检查用户是否已经登录
*
* */
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //spring提供的一个工具类用来
    //路径匹配器，支持统配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //* 1、获取本次请求的url
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",

        };
        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}",requestURI);
        //* 2、判断本次的url请求是否需要处理
        boolean check = check(urls,requestURI);

        //* 3、判断登录状态，如果已经登录、则直接放行

        if(check){
            filterChain.doFilter(request,response);
            return;
        }

        //* 4、判断登录状态，如果已经登录、则直接放行
        if (request.getSession().getAttribute("employee")!=null){

            Long employeeId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);

           /*此处有一个小bug 原本donFilter方法写在了if判断的条件之后 当登录之后就会直接放行
           * 不会在设置currentId导致后面用不了*/
            filterChain.doFilter(request,response);
            return;
        }
        //* 4-1、判断移动端登录状态，如果已经登录、则直接放行
        if (request.getSession().getAttribute("user")!=null){

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            /*此处有一个小bug 原本donFilter方法写在了if判断的条件之后 当登录之后就会直接放行
             * 不会在设置currentId导致后面用不了*/
            filterChain.doFilter(request,response);
            return;
        }
        //* 5、如果未登录则返回未登录的结果通过输出流响应客户端数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;





    }

    /**
     * 路径匹配
     * @param urls
     * @param requestUrl
     * @return
     */
    public boolean check(String [] urls ,String requestUrl){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match){
                return true;
            }
        }
        return false;
    }

}
